import React from "react";
import { createRoot, Root } from "react-dom/client";
import { ThemeProvider } from "@mui/material/styles";
import theme from "../theme";
import { generateUniqueId } from "@/utils";

/**
 * 组件渲染器类
 * 用于动态渲染 React 组件到 DOM
 */
export class ComponentRenderer<P extends Record<string, any>, T extends Partial<P>> {
  /** 容器 */
  private container: HTMLDivElement;
  /** React root */
  private root: Root;
  /** 组件 */
  private Component: React.ComponentType<T>;
  /** 组件属性 */
  private props: T;
  /**
   * 创建组件渲染器实例
   * @param Component 要渲染的 React 组件
   * @param props 组件属性
   */
  constructor(Component: React.ComponentType<T>, props: T = {} as T) {
    this.Component = Component;
    this.props = props;
    // 创建容器
    this.container = document.createElement("div");
    document.body.appendChild(this.container);
    this.container.id = generateUniqueId();
    this.root = createRoot(this.container);
    this.render();
  }

  /**
   * 渲染组件
   */
  private render(): void {
    const componentProps = {
      ...this.props,
      unmount: this.unmount.bind(this),
    };
    this.root.render(
      <ThemeProvider theme={theme}>
        <this.Component {...componentProps} />
      </ThemeProvider>
    );
  }
  /**
   * 卸载组件
   */
  unmount(): void {
    this.root.unmount();
    if (this.container.parentNode) {
      this.container.parentNode.removeChild(this.container);
    }
  }
}
